package com.cy.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import sun.audio.AudioData;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;

/**
 * 音乐播放器
 * @author CY
 *
 */
public class MusicPlay {
    private AudioStream as = null; // 单次播放声音用
    private ContinuousAudioDataStream cas = null;// 循环播放声音
    private AudioData audioData = null;// 存储循环播放的声音数据
    /**
     * 播放一次的构造函数
     * @param path 要播放的文件
     */
    public MusicPlay(String path) {
        try {
            // 打开一个声音文件流作为输入
            as = new AudioStream(new FileInputStream(path));
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 循环播放构造函数
     * @param path
     * @param continuous
     */
    public MusicPlay(String path, boolean continuous) {
    	FileInputStream fis = null;
    	BufferedInputStream bis = null;
    	ByteArrayOutputStream baos = null;
    	
    	try {
			fis = new FileInputStream(path);
			bis = new BufferedInputStream(fis);
			baos = new ByteArrayOutputStream();
			int c = bis.read();
			while(c != -1){
				baos.write(c);
				c = bis.read();
			}
			byte [] temp = baos.toByteArray();
			audioData = new AudioData(temp);
			cas = new ContinuousAudioDataStream(audioData);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(fis != null) {
					fis.close();
					fis = null;
				}
				if(bis != null) {
					bis.close();
					bis = null;
				}
				if(baos != null) {
					baos.close();
					baos = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
 
    /**
     *  一次播放 开始
     */
    public void play() {
        if(as == null) {
            System.out.println("AudioStream object is not created!");
        } else {
            AudioPlayer.player.start(as);
        }
    }
 
    /**
     *  一次播放 停止
     */
    public void stop() {
        if(as == null) {
            System.out.println("AudioStream object is not created!");
        } else {
            AudioPlayer.player.stop(as);
        }
    }
 
    /**
     *  循环播放 开始
     */
    public void continuousPlay() {
    	if(cas != null) {
    		AudioPlayer.player.start(cas);
    	} else {
    		System.out.println("ContinuousAudioDataStream object is not created!");
    	}
    }
 
    /**
     *  循环播放 停止
     */
    public void continuousStop() {
        if(cas != null) {
            AudioPlayer.player.stop(cas);
        } else {
        	System.out.println("ContinuousAudioDataStream object is not created!");
        }
    }
 
}
